/*
 * Copyright (c) 2001, Jan Nieuwenhuizen.
 *
 *     This program is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *     A copy of the GNU General Public License can be found at
 *     http://www.gnu.org/
 *
 * Written by Jan Nieuwenhuizen <janneke@gnu.org>
 * 
 * Modified by yospaly, 2009-1-20
 *
 */
#pragma once

#include "mounttable.h"

#define CYGWIN_POSTINSTALL_DIR	_T("/etc/postinstall/")
#define CYGWIN_PREREMOVE_DIR 	_T("/etc/preremove/")
#define CYGWIN_BASH_EXT 		_T("sh")
#define CYGWIN_CMD_EXT 			_T("bat")


class ScriptRunner {
public:
	static ScriptRunner& get() {
		return self;
	}
	
	enum STATUS_CODE {
		EXEC_SUCCESS = 0,
		SCRIPT_NOT_FOUND = 7,
		INCORRECT_FILE_EXT = 9,
	};
	
	wxString get_postinstall_dir() {
		return MountTable::get().cygpath(CYGWIN_POSTINSTALL_DIR);
	}
	wxString get_preremove_dir() {
		return MountTable::get().cygpath(CYGWIN_PREREMOVE_DIR);
	}
	
	/* Initialisation stuff for run_script: sh, cmd, CYGWINROOT and PATH */
	void init_run_script();
	
	/* Run the script.  If its suffix is .sh, and we have a Bourne shell, execute
	 it using sh.  Otherwise, if the suffix is .bat, execute using cmd.exe.  
	 Returns the exit status of the process, or negative error if any.  */
	long run_postinstall_script(const wxString& pkg,
			wxArrayString& output, wxArrayString& errors) const
	{
		return _run_script(CYGWIN_POSTINSTALL_DIR, pkg, CYGWIN_BASH_EXT,
						output, errors)
			& _run_script(CYGWIN_POSTINSTALL_DIR, pkg, CYGWIN_CMD_EXT,
						output, errors);
	}
	long run_preremove_script(const wxString& pkg,
			wxArrayString& output, wxArrayString& errors) const 
	{
		return _run_script(CYGWIN_PREREMOVE_DIR, pkg, CYGWIN_BASH_EXT,
						output, errors)
			& _run_script(CYGWIN_PREREMOVE_DIR, pkg, CYGWIN_CMD_EXT,
						output, errors);
		
	}
	
private:
	/* Run the script named dir/fname.ext
	 Returns the script exit status or negative error if any.  */
	long _run_script(const wxString& dir /* posix path */, const wxString& pkg,
			const wxString& ext, wxArrayString& output, wxArrayString& errors) const;

	wxString _sh;
	wxString _cmd;
	wxString _old_path;
    wxArrayString _shells;
	
	ScriptRunner();
	static ScriptRunner self;
};

